import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';

class PhotoApp extends StatefulWidget {
  const PhotoApp({super.key});

  @override
  State<PhotoApp> createState() => _PhotoAppState();
}

class _PhotoAppState extends State<PhotoApp> {
  List<File> list = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '拍照',
      theme: ThemeData(
        fontFamily: "jcjdht",
        colorScheme:
            ColorScheme.fromSeed(seedColor: ColorUtil.color('#f2f2f2')),
        useMaterial3: true,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('拍照'),
        ),
        body: list.isEmpty
            ? const Text("data")
            : Container(
                child: Wrap(spacing: 5, runSpacing: 5, children: _children()),
              ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _pickImage();
          },
          child: const Icon(Icons.party_mode),
        ),
      ),
    );
  }

  Future getLostData(ImageSource source) async {
    Navigator.pop(context);
    final ImagePicker picker = ImagePicker();
    var image = await picker.pickImage(source: source);
    Logger().i(image?.path);
    setState(() {
      list.add(File(image!.path));
    });
  }

  void _pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (cntext) => Container(
              height: 160,
              child: Column(
                children: [_item('拍照', true), _item('相册', false)],
              ),
            ));
  }

  _item(String s, bool b) {
    return GestureDetector(
      child: ListTile(
        title: Text(s),
        leading: b ? const Icon(Icons.party_mode) : const Icon(Icons.camera),
        onTap: () {
          getLostData(b ? ImageSource.camera : ImageSource.gallery);
        },
      ),
    );
  }

  _children() {
    return list.map((file) {
      return Stack(
        children: [
          Text(file.path),
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.file(file, height: 80, fit: BoxFit.fill),
          ),
          Positioned(
            right: 5,
            top: 5,
            child: GestureDetector( // 手势
              child: ClipOval(
                child: Container(
                  padding: const EdgeInsets.all(1),
                  decoration: BoxDecoration(color: ColorUtil.color('000000')),
                  child: const Icon(Icons.close, size: 18, color: Colors.white),
                ),
              ),
              onTap: () {
                setState(() {
                  list.remove(file);
                });
              },
            ),
          )
        ],
      );
    }).toList();
  }
}
